package com.chapter14.Map_;

import java.util.*;

/**
 * @author 宋鑫宇
 * @version 1.0
 * Map的遍历方式
 */
public class MapFor {
    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("1", new Book("", 100));
        map.put("1", "123");
        map.put("2", "234");
        map.put("3", "234");
        map.put("4", null);
        map.put(null, "456");
        map.put("5", "567");
        //第一组：先取出所有的Key，通过Key取出对应的Value
        Set set = map.keySet();
        System.out.println("=========增强for======");
        //1.增强for
        for (Object o : set) {
            System.out.println(o + "=" + map.get(o));
        }
        System.out.println("=========迭代器========");
        //2.迭代器
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            Object next = iterator.next();
            System.out.println(next + "=" + map.get(next));
        }
        //第二组：先取出所有的Value取出，然后输出,直接取值
        System.out.println("==========第二组==========");
        System.out.println("=======增强for=======");
        Collection values = map.values();
        for (Object o : values) {
            System.out.println(o);
        }
        System.out.println("=======迭代器======");
        Iterator iterator1 = values.iterator();
        while (iterator1.hasNext()) {
            Object next = iterator1.next();
            System.out.println(next);
        }
        //第三组：通过EntrySet获取Key和Value
        System.out.println("=======第三组=======");
        Set set1 = map.entrySet();
        //增强for
        System.out.println("=======增强for=====");
        for (Object entry : set1) {
            //entry对象转成Map.Entry
            Map.Entry e = (Map.Entry) entry;
            System.out.println(e.getKey() + " = " + e.getValue());
        }
        //迭代器
        System.out.println("=====迭代器======");
        Iterator iterator2 = set1.iterator();
        while (iterator2.hasNext()) {
            Object next = iterator2.next();
            //把next 转成Map.Entry ，向下转型
            Map.Entry next1 = (Map.Entry) next;
            System.out.println(next1);
        }

    }
}
